package com.onairm.baselibrary.net;

import android.text.TextUtils;

import com.onairm.baselibrary.Init;
import com.onairm.baselibrary.net.interceptor.CacheInteceptor;
import com.onairm.baselibrary.net.interceptor.LogInterceptor;
import com.onairm.baselibrary.utils.GsonUtil;
import com.onairm.baselibrary.utils.Utils;
import com.tamic.novate.BaseInterceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by apple on 17/11/2.
 */

public class RetrofitManager {

    public static final String TAG = "RetrofitManager";
    private Retrofit retrofit;

    private static String baseUrl;
    private static Map<String, Builder> map;

    private RetrofitManager(Builder builder) {
        retrofit = builder.retrofit;
    }

    public <T> T createReq(Class<T> reqServer) {
        return retrofit.create(reqServer);
    }

    public static void setBaseUrl(String baseUrl) {
        RetrofitManager.baseUrl = baseUrl;
        map = new HashMap<>();
    }

    public static Builder createBuilder(String key) {
        if (map == null) {
            map = new HashMap<>();
        }
        if (map.containsKey(key)) {
            Builder builder = map.get(key);
            builder.key = key;
            return builder;
        } else {
            Builder builder = new Builder();
            builder.key = key;
            map.put(key, builder);
            return builder;
        }
    }

    /**
     * 用于基础参数变化时的重置
     */
    public static void reset() {
        if (map == null) {
            map = new HashMap<>();
        }
        map.clear();
    }

    public static class Builder {
        private OkHttpClient.Builder okClientBuilder;
        private Retrofit.Builder retrofitBuilder;
        private Retrofit retrofit;
        private String key;

        private String builderBaseUrl;
        private int connectTime = 15;
        private int readTime = 20;
        private int writeTime = 20;
        private ResAndReqInterceptor resAndReqInterceptor;

        public Builder() {
            okClientBuilder = new OkHttpClient.Builder();
            retrofitBuilder = new Retrofit.Builder();
            resAndReqInterceptor = new ResAndReqInterceptor();
            okClientBuilder.addInterceptor(resAndReqInterceptor);//添加基础参数
        }

        public Builder writeTimeout(int time) {
            connectTime = time;
            return this;
        }

        public Builder readTimeout(int time) {
            readTime = time;
            return this;
        }

        public Builder connectTimeout(int time) {
            connectTime = time;
            return this;
        }

        public Builder setBaseUrl(String builderBaseUrl) {
            this.builderBaseUrl = builderBaseUrl;
            return this;
        }

        public <T> Builder addParameters(Map<String, T> parameters) {
            if (okClientBuilder == null) {
                throw new IllegalStateException("OkHttpClientBuilder required.");
            }
            okClientBuilder.addInterceptor(new BaseInterceptor(parameters));
            return this;
        }

        public Builder addCache() {
            if (okClientBuilder == null) {
                throw new IllegalStateException("OkHttpClientBuilder required.");
            }
            okClientBuilder.addInterceptor(new CacheInteceptor(true, key));
            return this;
        }

        public Builder addInterceptor(Interceptor interceptor) {
            if (okClientBuilder == null) {
                throw new IllegalStateException("OkHttpClientBuilder required.");
            }
            okClientBuilder.addInterceptor(interceptor);
            return this;
        }

        public RetrofitManager build() {
            if (baseUrl == null) {
                throw new IllegalStateException("Base URL required.");
            }
            if (okClientBuilder == null) {
                throw new IllegalStateException("OkHttpClientBuilder required.");
            }
            if (retrofitBuilder == null) {
                throw new IllegalStateException("RetrofitBuilder required.");
            }
            okClientBuilder.connectTimeout(connectTime, TimeUnit.SECONDS)
                    .readTimeout(readTime, TimeUnit.SECONDS)
                    .writeTimeout(writeTime, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true);

            if (true) {
                okClientBuilder.addInterceptor(new LogInterceptor(key)); //添加retrofit日志打印
            }
            OkHttpClient okHttpClient = okClientBuilder.build();

            if (!TextUtils.isEmpty(builderBaseUrl)) {
                retrofitBuilder.baseUrl(builderBaseUrl);
            } else {
                retrofitBuilder.baseUrl(baseUrl);
            }
            retrofit = retrofitBuilder.addConverterFactory(
                    CustomGsonConverterFactory.create(GsonUtil.buildGson()))// 在数据解析的时候处理resopnseCode
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();

            return new RetrofitManager(this);
        }
    }
}
